import {URLs} from "@/config/index.js";
import { toast } from '@/utils/uni-api.js'
import store from '@/store/index.js'
// 可重复请求的白名单
const whiteList = ['/common/api/getCity', '/equipment/product/getProductByCategory'];
// 校验重复请求的方法
const checkRepeat = checkRepeatRequest()

/**
 * 请求数据封装方法
 * @param method 请求方式 GET POST PUT
 * @param url 请求地址（login/login）
 * @param data 请求数据
 * @param loading 是否展示loading
 * @param loadingTitle 展示loading文字
 * @returns {Promise<unknown>}
 */
function request(method, url, data = {}, loading = false, loadingTitle = "请求中", loadingMask = true) {
	// 校验是否是重复请求
	checkRepeat(url).catch(err => {
		toast('请不要重复请求')
		return Promise.reject()
	})
	
	loading && uni.showLoading({
		title: loadingTitle,
		mask: loadingMask
	})
	const header = {
		'content-type': 'application/json;charset=UTF-8',
	}
	if(store.getters.isLogin){
		header['X-Access-Token'] = store.getters.token
	}
	return new Promise((resolve, reject) => {
		//发起请求
		uni.request({
			url: URLs.host + url,
			method,
			data,
			header,
			success: res => {
				loading && uni.hideLoading()
				let code = res.data.code
				let message = res.data.message;
				// 请求成功
				if(code == 200){
					resolve(res.data)
				}
				// 未登录
				else if(code == 401){
					store.dispatch('user/logout');
					reject(message)
					toast('登录已过期，请重新登录', true)
					setTimeout(() => {
						uni.navigateTo({
							url:'/pages/user/login'
						})
					}, 1000)
				}else{
					toast(message)
					reject(message)
				}
			},
			fail: err => {
				console.log(err)
				loading && uni.hideLoading()
				toast(err)
				reject(err)
			}
		});
	})
}

/**
 * 校验是否是重复请求
 * @param {Object} url
 */
function checkRepeatRequest(){
	// 上次请求地址
	let beforeReq = '';		
	// 上次请求时间
	let beforeReqTime = 0	
	// 判断重复请求的计算时间 单位:ms
	const betweenTime = 300 
	
	return function(url){
		const nowTime = new Date().getTime()
		// 不在白名单内，且此次请求与上次请求一致且间隔时间小于300毫秒视为重复请求
		if(whiteList.indexOf(url) == -1 && url == beforeReq && nowTime - beforeReqTime < betweenTime){
			console.log('本次请求与上次请求重复，本次请求:' + url + '，上次请求:' + beforeReq);
			beforeReq = url
			beforeReqTime = nowTime
			return Promise.reject()
		}
		// 正常请求
		else{	
			beforeReq = url
			beforeReqTime = nowTime
			return Promise.resolve()
		}
	}
}

let requests = {}
const types = ['get', 'post', 'put', 'delete']
types.forEach(item => {
	requests[item] = function (url, params, loading, loadingTitle){
		return request(item, url, params, loading, loadingTitle)
	}
})

export default requests
